#include "event_loop_thread.h"
#include "event_loop.h"
#include "thread.h"
#include "event_loop_thread.h"

using namespace el;

EventLoopThread::EventLoopThread()
{
	thread_ = new Thread;
	loop_ = NULL;
}

EventLoopThread::~EventLoopThread()
{
	quit();
	delete thread_;
	thread_ = NULL;
}

EventLoop * el::EventLoopThread::startLoop()
{
	assert(NULL == loop_);
	Functor process(this, &EventLoopThread::run);
	thread_->start(process);
	while (true)
	{
		event_lock_.wait(10);
		MutexLockGuard lock(mutex_);
		if (loop_)
		{
			return loop_;
		}
	}
}


void el::EventLoopThread::run()
{
	EventLoop loop;
	{
		MutexLockGuard lock(mutex_);
		loop_ = &loop;
	}
	event_lock_.pulseEvent();
	loop.loop();
	MutexLockGuard lock(mutex_);
	loop_ = NULL;
}

void el::EventLoopThread::quit()
{
	if (!thread_)
	{
		return;
	}
	{
		MutexLockGuard lock(mutex_);
		if (NULL != loop_)
		{
			loop_->quit();
		}
	}
	thread_->wait();
}

void el::EventLoopThread::waitLoop()
{
	thread_->wait();
}
